const {exec} = require('../db/mysql')
const xss = require('xss')
const getList = async (author, keyword) => {
  let sql = `select id, title, content, createtime, author from blogs where 1=1 `
  if (author) {
    sql += `and author = '${author}' `
  }
  if (keyword) {
    sql += `and title like '%${keyword}%' `
  }
  sql += `order by createtime desc;`
  console.log(sql);
  return await exec(sql)
  
  // exec(sql).then(res => {
  //   console.log(res);
  //   return res
  // })
  
}
const getDetail = async (id) => {
  let sql = `select * from blogs where id = '${id}'`
  console.log(sql);
  return await exec(sql).then(rows => {
    return rows[0]
  }) 
}
const newBlog = async (blogData = {}) => {
  // blogData 是一个博客对象，包含title，content属性
  const title = blogData.title
  const content = blogData.content
  const author = blogData.author
  const createTime = Date.now()
  let sql = `
  insert into blogs(title, content, author, createtime)
  values('${title}', '${content}', '${author}', '${createTime}');
  `
  console.log(sql);
  return await exec(sql).then(insertData => {
    console.log(insertData);
    return {
      id: insertData.insertId
    }
  })
}

const updateBlog = async (id, blogData = {}) => {
  // blogData 是一个博客对象，包含title，content属性
  const title = blogData.title
  const content = blogData.content
  let sql = `
    update blogs 
    set title = '${title}',content = '${content}'
    where id = ${id};
  `
  return await exec(sql).then(updateData => {
    if (updateData.affectedRows > 0 ){
      return true
    }
    return false
  })
}

const delBlog = async (id, author) => {
  // blogData 是一个博客对象，包含title，content属性
  let sql = `
    delete from blogs
    where id = ${id}
    and author = '${author}';
  `
  return await exec(sql).then(delData => {
    console.log(delData);
    if (delData.affectedRows > 0 ){
      return true
    }
    return false
  })
}
module.exports = {
  getList,
  getDetail,
  newBlog,
  updateBlog,
  delBlog
}